#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "pub_header.h"

int create_send_mess(char * str);
extern int sxsb_get_rsakey();
extern char * get_xml_data(const char * xmlFile);
extern char * sxsb_rsa_get_sign_byprikey(const char * xmlFile);
extern uint32 l_htonl(uint32 hl);
extern uint32 l_ntohl(uint32 nl);
static char XML_FILE[100];
static char OPENSSLKEY[100];
static char PUBLICKEY[100]; 

int main(int argc,char *argv[])
{
	if(argc < 3)
	{
		printf("缺少参数,报文名称,密钥名称");
		return -1;
	}
	sprintf(XML_FILE,"%s",argv[1]);
	printf("报文名称:%s\n",XML_FILE);

	snprintf(OPENSSLKEY,sizeof(OPENSSLKEY),"/home/ap/sxclp2/etc/sxsbzldf/%s.local.pri.key",argv[2]);
	snprintf(PUBLICKEY,sizeof(PUBLICKEY),"/home/ap/sxclp2/etc/sxsbzldf/%s.pub.key",argv[2]);
	printf("公钥:%s\n",OPENSSLKEY);
	printf("私钥:%s\n",PUBLICKEY);

	int clientSocket = 0;
	struct sockaddr_in s_add;
	int iDataNum;
	char sendbuf[2048] = {'\0'};

	clientSocket = socket(AF_INET,SOCK_STREAM,0);
	if(-1 == clientSocket)
	{
			printf("socket fail \n");
			return -1;
	}
	printf("socket success ! \n");
	bzero(&s_add,sizeof(struct sockaddr_in));
	s_add.sin_family = AF_INET;
	s_add.sin_addr.s_addr = inet_addr(SERVER_ADDR);
	s_add.sin_port = htons(SERVER_PORT);
	printf("s_add %#x, port %#x \n",s_add.sin_addr.s_addr,s_add.sin_port);
	if(-1 == connect(clientSocket,(struct sockaddr *)(&s_add),sizeof(struct sockaddr)))
	{
			printf("connect is fail \n");
			return -1;
	}
	printf("connect is success \n");
	printf("连接到主机..\n");
	int dataLength = create_send_mess(sendbuf);
	uint32 n_data = l_htonl((uint32)dataLength);
	printf("发送消息\n");
	send(clientSocket,&n_data,4,0);
	send(clientSocket,sendbuf,strlen(sendbuf),0);
	printf("%s \n",sendbuf);
	printf("发送完成..\n");
	
	
	printf("读取消息..\n");
	unsigned int result_nl = 0 ;
	recv(clientSocket,(unsigned int *)(&result_nl),4,0);
	printf("%#x \n",result_nl);
	uint32 result_hl = l_ntohl(result_nl);
	printf("转换之后 %ld " , result_hl);
	
	char recvbuf[result_hl+1];
	iDataNum = recv(clientSocket,recvbuf,result_hl+1,0);
	recvbuf[iDataNum] = '\0';
	printf("接收到的消息是:%s\n",recvbuf);       

	close(clientSocket);
	return 0;
}

int create_send_mess(char * str)
{
	sxsb_get_rsakey(OPENSSLKEY,PUBLICKEY);
	char * xmlData = get_xml_data(XML_FILE);
	char * xmlData2 = sxsb_rsa_get_sign_byprikey(XML_FILE);
	long len1 = strlen(xmlData);
	long len2 = strlen(xmlData2);
	strcat(str,xmlData);
	strcat(str,xmlData2);
	free(xmlData);
	free(xmlData2);
	return len1 + len2;
}
